package com.surelution.projects.crm

import groovy.time.TimeCategory;

/**
 * 
 * @author <a href="mailto:guangzong.syu@gmail.com">Guangzong</a>
 *
 */
class MarketSaleSumService {

    static transactional = true

	def sumMonthSales(Long marketId, Date month) {
		Float gaso = 0
		Float diesel = 0
		def nextMonth
		use(TimeCategory) {
			nextMonth = month + 1.month
		}
		def market = Market.get(marketId)
		def result = CardConsume.createCriteria().list {
			createAlias("member","m")
			eq("m.market", market)
			ge("tradeTime", month)
			lt("tradeTime", nextMonth)
		}
		Date now = new Date()
		
		if(result) {
			result.each {
				def min = 1000
				GasType type = it.gasType
				def d = GasDensity.createCriteria().list() {
					eq("type", type)
					order("time", "desc")
				}
				if(d) {
					min = d.min{}
				}
				if(it.gasType.category.code == GasTypeCategory.CODE_DIESEL) {
					
					diesel += it.amount*(min.density-1.1)/1000000
				}
				if(it.gasType.category.code == GasTypeCategory.CODE_GASO) {
					gaso += it.amount*(min.density-1.1)/1000000
				}
			}
		}
		def sum = MarketGasSale.createCriteria().get {
			eq("market", market)
			eq("saleGasTime", month)
			eq("sumType", MarketGasSale.SUM_TYPE_MONTH)
		}
		if(!sum) {
			sum = new MarketGasSale(saleGasTime:month,
					sumType:MarketGasSale.SUM_TYPE_MONTH)
			sum.saleNumber = gaso
			sum.dieselOilNumber = diesel
			sum.market = market
			println "${month},${gaso},${diesel},${market.id}"
//			market.addToMarketGasSales(sum)
			sum.save(flush:true)
			//				sum.save()
		} else {
			sum.saleNumber = gaso
			sum.dieselOilNumber = diesel
		}
	}
	
	def echo(){
		println "get here${System.currentTimeMillis()}"
	}
}
